-- watchram.lua
-- Displays a formatted block of RAM values.
-- Use:
-- You can click on a value to highlight it.
-- The table 'desired_values' will make values green if they appear.
-- Contributors: bahamete

-- TODO: Reorganize this. Severely.

-- The RAM to display
local RAMStart = 0x7E0322
local RAMEnd = 0x7E0351

-- Transparency of table and values
local transparency = 1.5

-- Number of values to have in a row
local row_length  = 16

-- Colors of the boxes
local ramboxcolor = "#555555"
local valboxcolor = "#888888"

-- A table of values that will be colored green if they show up.
local desired_values = {
  0xF4, 0x62, 0xD4
}

-- Probably best to just ignore these
local values = {}
local num_rows    = (RAMEnd - RAMStart) / row_length
local num_values  = RAMEnd - RAMStart
for i = 0, num_values do values[i + 1] = { ["highlight"] = "false" } end

-- Thanks, FatRatKnight!
local keys, lastkeys= input.get(), input.get()
local function UpdateKeys() lastkeys= keys;  keys= input.get() end
local function Press(k) return keys[k] and (not lastkeys[k]) end

local print_ram = function(xstart, ystart)
  UpdateKeys()
  local dx, dy = 0, 0
  local xramprint = xstart + string.len(RAMStart) * 4 + 5
  local yramprint = ystart

  gui.box(xstart - 4, ystart - 2, xstart + 2 + string.len(RAMStart) * 4, (ystart + num_rows * 8), ramboxcolor, "#000000")
  gui.box(xramprint - 3, ystart - 2, xramprint + row_length * 12, (ystart + num_rows * 8), valboxcolor, "#000000")

  for i = 0, num_rows do
    gui.text(xstart, ystart + i * 8, string.format("$%X", RAMStart + i * 16))
  end

  for i = 0, num_values do
    local n = i + 1

    values[n].val = memory.readbyte(RAMStart + i)
    values[n].x = (xramprint + dx * 12) + 1
    values[n].y = yramprint + dy

    if keys.xmouse >= values[n].x and keys.xmouse <= values[n].x + 8 and
    keys.ymouse >= values[n].y and keys.ymouse < values[n].y + 8 then
      gui.transparency(0); gui.text(0, 0, string.format("$%X",RAMStart + i)); gui.transparency(transparency);
      if Press("leftclick") then
        values[n].highlight = values[n].highlight == "true" and "false" or "true"
        --emu.message(string.format("Started watching $%X", RAMStart + i))
      end
    end

    if values[n].highlight == "true" then
      gui.transparency(0)
    end

    local color = "#FFFFFF"
    for k, v in pairs(desired_values) do
      if values[n].val == v then
        color = "#00FF00"
      break
      end
    end

    gui.text(values[n].x, values[n].y, string.format("%02X", values[n].val), color)

    if (i + 1) % (row_length) == 0 and i ~= 0 then
      dx = 0; dy = dy + 8
    else
      dx = dx + 1
    end
    gui.transparency(transparency)
  end
end

local main = function()
  print_ram(16, 30)
end

gui.register(function()
  gui.transparency(transparency)
  main()
end)
